﻿

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
using XUCore.Serializer;

namespace XUCore.Extensions
{
    /// <summary>
    /// 缓存(<see cref="IDistributedCache"/>) 扩展
    /// </summary>
    public static partial class IDistributedCacheExtensions
    {
        /// <summary>
        /// 获取/写入缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T GetOrSet<T>(this IDistributedCache cache, string key, Func<T> factory, DistributedCacheEntryOptions options) where T : class
        {
            var value = cache.GetString(key);

            if (value.IsEmpty())
            {
                var data = factory();

                value = data.ToJson();

                cache.SetString(key, value, options);
            }
            return value.ToObject<T>();
        }
        /// <summary>
        /// 获取/写入缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static async Task<T> GetOrSetAsync<T>(this IDistributedCache cache, string key, Func<T> factory, DistributedCacheEntryOptions options, CancellationToken cancellationToken = default) where T : class
        {
            var value = await cache.GetStringAsync(key, cancellationToken);

            if (value.IsEmpty())
            {
                var data = factory();

                value = data.ToJson();

                await cache.SetStringAsync(key, value, options, cancellationToken);
            }
            return value.ToObject<T>();
        }
    }
}